import { defineStore } from 'pinia';
import { ref } from 'vue';
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user/index.ts';
import type { UserLoginData } from '@/api/user/type.ts';
import type { UserInfo } from '../types/user.ts';
import router from '@/router/index.ts';
import { constantRoutes, asyncRoutes, anyRoutes } from '@/router/routes.ts';
import type { RouteRecordRawConfig } from '@/router/type.ts';
import cloneDeep from 'lodash/cloneDeep.js';

// 路由处理函数
function filterAsyncRoutes(
  routes: string[],
  asyncRoutes: RouteRecordRawConfig[]
) {
  return asyncRoutes.filter(route => {
    const flag = routes.includes(route.name as string);
    if (!flag) return false;
    if (route.children && route.children.length > 0) {
      route.children = filterAsyncRoutes(routes, route.children);
    }
    return true;
  });
}

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref<string>();
    const userInfo = ref<UserInfo>();
    const menuRoutes = ref<RouteRecordRawConfig[]>(constantRoutes);
    const buttons = ref<string[]>();

    // 存储添加的异步路由返回的回调函数用于removeRoute
    const addRoutesRemoveArr: Array<() => void> = [];

    // 用户登录
    async function userLogin(data: UserLoginData) {
      const result = await reqLogin(data);
      if (result.code === 200) {
        // 登录成功
        token.value = result.data;
        return 'ok';
      } else {
        // 登录失败
        return Promise.reject(new Error(result.message));
      }
    }

    async function getUserInfo() {
      const result = await reqUserInfo();
      if (result.code === 200) {
        userInfo.value = {
          name: result.data.name,
          avatar: result.data.avatar
        };
        buttons.value = result.data.buttons;

        // 动态路由
        const accessedRoutes = filterAsyncRoutes(
          result.data.routes,
          cloneDeep(asyncRoutes)
        );
        menuRoutes.value = [...constantRoutes, ...accessedRoutes, ...anyRoutes];
        [...accessedRoutes, ...anyRoutes].forEach(route => {
          if (!router.hasRoute(route.name!)) {
            addRoutesRemoveArr.push(router.addRoute(route));
          }
        });
        return 'ok';
      } else {
        // token失效
        return Promise.reject(new Error('token过期，请重新登陆'));
      }
    }
    // 重置数据
    function resetAll() {
      token.value = undefined;
      userInfo.value = undefined;
      buttons.value = undefined;
      menuRoutes.value = constantRoutes;
      // 应该重置路由
      // 删除添加的路由
      addRoutesRemoveArr.forEach(fn => fn());
    }

    // 退出登录
    async function logout() {
      const result = await reqLogout();
      if (result.code === 200) {
        resetAll();
        return 'ok';
      } else {
        return Promise.reject(new Error('退出登录失败'));
      }
    }

    return {
      token,
      userLogin,
      getUserInfo,
      resetAll,
      userInfo,
      logout,
      menuRoutes,
      buttons
    };
  },
  {
    persist: {
      paths: ['token']
    }
  }
);
